$(function()
{

	// 初始化表格 ---未分配订单
	var $notAssignPanel = $("#dop_datagrid_delivery");
	var notAssignGrid = $notAssignPanel.datagrid.bind($notAssignPanel);
	notAssignGrid({
		url : "",
		height : 300,
		title : "未分配订单",
		pagination : true,
		fitColumns : false,
		singleSelect : false,
		fit : false,
		pageSize : 10,
		pageList : [10, 20, 30, 50],
		sortOrder : 'desc',
		rownumbers : true,
		showFooter : true,
		frozenColumns : [[]],
		columns : [[{
			field : 'ck',
			checkbox : true,
			hidden : true
		}, {
			field : "id",
			width : 150,
			title : "主键",
			hidden : true
		}, {
			field : "code",
			width : 150,
			title : "编码",
			align:'center'
		}, {
			field : "statusText",
			width : 120,
			title : "状态",
			align:'center',
			formatter:function(value,row,index){
				if(row.readyStatus==1&&row.status==3){
					return value+"("+row.readyStatusStr+")";
				}else if(row.readyStatus==2&&row.status==4){
					return value+"("+row.readyStatusStr+")";
				}
				return value;
			}
		}, {
			field : "detail",
			width : 250,
			title : "订单明细",
			halign:"center",
			align:'left'
		}, {
			field : "custName",
			width : 80,
			title : "客户姓名",
			align:'center'
		}, {
			field : "telephone",
			width : 100,
			title : "电话",
			halign:"center",
			align:'left'
		}, {
			field : "custAddress",
			width : 280,
			title : "客户地址",
			halign:"center",
			align:'left'
		}, {
			field : "note",
			width : 300,
			title : "备注",
			halign:"center",
			align:'left'
		}, {
			field : "createDate",
			width : 120,
			title : "下单日期",
			align:'center',
			formatter:function(value,row,index){
				return new Date(value).format("yyyy-MM-dd hh:mm");
			}
		}, {
			field : "askSendTime",
			width : 120,
			title : "要求送达时间",
			align:'center',
			formatter:function(value,row,index){
				if(value==null){
					return "";
				}
				return new Date(value).format("yyyy-MM-dd hh:mm");
			}
		}, {
			field : "payMethodText",
			width : 80,
			title : "支付方式",
			align:'center'
		},  {
			field : "totalPrice",
			width : 80,
			title : "订单金额",
			halign:"center",
			align:'right'
		},{
			field : "orderTotalPrice",
			width : 80,
			title : "订单总金额",
			halign:"center",
			align:'right'
		},
		/*{
			field : "needWarmBoxText",
			width : 150,
			title : "需要保温箱",
			align:'center'
		},
		*/ {
			field : "storefrontName",
			width : 150,
			title : "店面",
			halign:"center",
			align:'left'
		}]]
	});

	// 初始化表格 -- 已经分配的订单
	var $assignPanel = $("#dop_datagrid_delivery1");
	var assignGrid = $assignPanel.datagrid.bind($assignPanel);
	assignGrid({
		url : "",
		height : 300,
		title : "已分配订单",
		pagination : true,
		fitColumns : false,
		singleSelect : false,
		fit : false,
		pageSize : 10,
		pageList : [10, 20, 30, 50],
		sortOrder : 'desc',
		rownumbers : true,
		showFooter : true,
		frozenColumns : [[]],
		columns : [[{
			field : 'ck',
			checkbox : true,
			hidden : true
		}, {
			field : "id",
			width : 150,
			title : "主键",
			hidden : true
		}, {
			field : "code",
			width : 150,
			title : "编码",
			align:'center'
		},{
			field : "statusText",
			width : 120,
			title : "状态",
			align:'center',
			formatter:function(value,row,index){
				if(row.readyStatus==1&&row.status==3){
					return value+"("+row.readyStatusStr+")";
				}else if(row.readyStatus==2&&row.status==4){
					return value+"("+row.readyStatusStr+")";
				}
				return value;
			}
		},{
			field : "detail",
			width : 250,
			title : "订单明细",
			halign:"center",
			align:'left'
		}, {
			field : "deliveryManName",
			width : 100,
			title : "员工姓名",
			align:'center'
		}, {
			field : "custName",
			width : 80,
			title : "客户姓名",
			align:'center'
		}, {
			field : "telephone",
			width : 100,
			title : "电话",
			halign:"center",
			align:'left'
		}, {
			field : "custAddress",
			width : 280,
			title : "客户地址",
			halign:"center",
			align:'left'
		}, {
			field : "note",
			width : 300,
			title : "备注",
			halign:"center",
			align:'left'
		}, {
			field : "createDate",
			width : 120,
			title : "下单日期",
			align:'center',
			formatter:function(value,row,index){
				return new Date(value).format("yyyy-MM-dd hh:mm");
			}
		}, {
			field : "askSendTime",
			width : 120,
			title : "要求送达时间",
			align:'center',
			formatter:function(value,row,index){
				if(value==null){
					return "";
				}
				return new Date(value).format("yyyy-MM-dd hh:mm");
			}
		},{
			field : "payMethodText",
			width : 80,
			title : "支付方式",
			align:'center'
		},{
			field : "totalPrice",
			width : 80,
			title : "订单金额",
			halign:"center",
			align:'right'
		},{
			field : "orderTotalPrice",
			width : 80,
			title : "订单总金额",
			halign:"center",
			align:'right'
		},
		/*{
			field : "needWarmBoxText",
			width : 150,
			title : "需要保温箱",
			align:'center'
		},
		*/
		{
			field : "storefrontName",
			width : 150,
			title : "店面",
			halign:"center",
			align:'left'
		}]]
	});

	// 刷新表格数据--- 未分配订单
	function getNotAssignOrder()
	{
		updateOrders(notAssignGrid, [1]);
	};

	// 刷新表数据------已分配订单
	function getAssignedOrder()
	{
		updateOrders(assignGrid, [2, 3, 4, 8, 9, 11]);
	};

	function updateOrders(grid, params)
	{
		var options = grid('getPager').data("pagination").options;
		var pageSize = options.pageSize;	// 每页显示的个数
		var pageNum = options.pageNumber;   // 页数
		var params = $.extend({
			pageNum : pageNum,
			pageSize : pageSize
		}, {
			// 未分配
			statusList : params
		});
		EapTools.doAction("orderQueryController.do?getOrderListByStatus", params, true, function(data)
		{
			if(!ExpLink.Utility.isDefAndNotNull(data))
			{
				return;
			}

			// 首先设定表格中数据的个数
			var gridData = grid('getData');

			var existsRows = gridData.rows;
			var newData = data.list;

			var removeRows = ExpLink.algo.linq(existsRows).difference(newData, function(ele)
			{
				return ele.id;
			}).toArray();

			for (var int3 = 0, length = removeRows.length; int3 < length; int3++)
			{
				var rowIndex = grid('getRowIndex', removeRows[int3]);
				grid('deleteRow', rowIndex);
			}

			var newRows = ExpLink.algo.linq(newData).difference(existsRows, function(ele)
			{
				return ele.id;
			}).toArray();

			for (var int2 = 0,length=newRows.length ; int2 < length; int2++)
			{
				grid('appendRow', newRows[int2]);
			}

			// 根据返回的pageNumber 更新之
			grid('getPager').data("pagination").options.pageNumber = data.pageNumber;
			grid('getPager').pagination({total:data.count});
			// 如果没有数据改变 ， 模拟数据更新 . 主要为修改表格显示的数据总数
//			if(removeRows.length == 0 && newRows.length == 0)
//			{
//				grid('deleteRow', existsRows.length-1);
//				gridData.total = data.count - 1;
//				grid('appendRow', newData[newData.length-1]);
//			}
			
			
		});
	};

	// 初始化表格 并定时刷新
	getNotAssignOrder();
	getAssignedOrder();
	setInterval(getNotAssignOrder, 5000);
	setInterval(getAssignedOrder, 5000);

	
	//关联分页中页码修改事件
	notAssignGrid('getPager').pagination({onSelectPage:function(pageNumber,pageSize){
		updateOrders(notAssignGrid, [1]);
	}});
	
	assignGrid('getPager').pagination({onSelectPage:function(pageNumber,pageSize){
		updateOrders(assignGrid,[2,3,4]);
	}});
	
	
	
});

loadDeliverMan();
$("#dop_btn_distribution").click(function(){
	var seleted=$("#dop_datagrid_delivery").datagrid("getSelections");
	if(seleted.length>0){
		layerIndex=$.layer({
			type:1,
	 		shadeClose : true,
	 		title : '<div><span style="line-height: 14px;">选择配送人员</span></div>',
			more:true,
			area : [ "450", "100" ],
			page : {
				dom : '#deliveryManDiv'
			}
		});
	}else{
		layerComm("请选择订单!","dop_btn_distribution");
	}
});

/**
 * 确认分配人员
 */
$("#divide_ok").click(function(){
	var seleted=$("#dop_datagrid_delivery").datagrid("getSelections");
	var arr=[];
	for(var i=0;i<seleted.length;i++){
		arr.push(seleted[i].id);
	}
	
	EapTools.doAction("storefrontAcceptController.do?delive", {ids:arr,manId:$("#deliveryManList").val()},
		true, function(data) {
			layer.close(layerIndex);
			layer.alert("操作成功！", 1);
			init();
	});
	
});

/**
 * 异步加载配送人员
 */
function loadDeliverMan(){
	var list=$("#deliveryManList");
	list.children().remove();
	EapTools.doAction("deliveryManController.do?getOpenAndReceiveDeliveryMan", null,
		true, function(data) {
			for(var i=0;i<data.length;i++){
				list.append("<option value="+data[i].id+">"+data[i].name+"</option>");
			}
	});
}

/***
 * layer提示信息封装
 * @param msg  消息内容
 * @param id   要显示位置的元素ID
 */
function layerComm(msg,id){
	layer.tips(msg, document.getElementById(id), {
		guide : 2,
		time : 3,
		more:true
	});
}
/**
 * 格式化日期
 * @param {} fmt
 * @return {}
 */
Date.prototype.Format = function(fmt) 
{ //author: meizz 
  var o = { 
    "M+" : this.getMonth()+1,                 //月份 
    "d+" : this.getDate(),                    //日 
    "h+" : this.getHours(),                   //小时 
    "m+" : this.getMinutes(),                 //分 
    "s+" : this.getSeconds(),                 //秒 
    "q+" : Math.floor((this.getMonth()+3)/3), //季度 
    "S"  : this.getMilliseconds()             //毫秒 
  }; 
  if(/(y+)/.test(fmt)) 
    fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length)); 
  for(var k in o) 
    if(new RegExp("("+ k +")").test(fmt)) 
  fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length))); 
  return fmt; 
}

